package com.fitz.remote.client.pool;

import com.fitz.registry.InstanceInfo;
import com.fitz.remote.client.ConsumerClient;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fitz
 * Created  on 2020/5/26
 */
public class ConsumerClientFactory implements PooledObjectFactory<ConsumerClient> {

    private static final Logger logger = LoggerFactory.getLogger(ConsumerClientFactory.class);

    private InstanceInfo node;

    ConsumerClientFactory(InstanceInfo node) {
        this.node = node;
    }

    @Override
    public PooledObject<ConsumerClient> makeObject() throws Exception {
        try {
            ConsumerClient client = new ConsumerClient(node);
            client.connect();
            client.open();
            logger.info("makeObject connect server success:[{}:{}]",node.getHost(),node.getPort());
            return new DefaultPooledObject<>(client);
        }catch (Exception e){
            logger.error("connect server failed",e);
            throw e;
        }
    }

    @Override
    public void destroyObject(PooledObject<ConsumerClient> pooledObject) throws Exception {
        ConsumerClient client = pooledObject.getObject();
        logger.info("destroyObject open");
        if (client.isOpen()){
            client.close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<ConsumerClient> pooledObject) {
        ConsumerClient client = pooledObject.getObject();
        logger.info("validateObject open");
        return client.isOpen();
    }

    @Override
    public void activateObject(PooledObject<ConsumerClient> pooledObject) throws Exception {
        ConsumerClient client = pooledObject.getObject();
        if (!client.isOpen()){
            logger.info("activateObject Channel is closed,reopen");
            client.open();
        }
    }

    @Override
    public void passivateObject(PooledObject<ConsumerClient> pooledObject) throws Exception {
        ConsumerClient client = pooledObject.getObject();
        if (!client.isOpen()){
            logger.info("Channel is closed,reopen");
            client.open();
        }
    }
}
